<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\Common\CoordinateService;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportSiteMall extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'siteLocation-importMall';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入商场信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址');

        if (!$url) {
            $url = 'https://file.51kuafu.com/d6/99/aa91f041b78d468eeb1ff3fb6ca9a1f85d7851aa0e30cd4dad281cccc434.csv';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new SiteMall(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class SiteMall implements ToCollection
{

    private string $errMsg = '';

    private array $ratingArr = [];

    public function collection(Collection $collection)
    {
        // 校验列名信息
        $this->checkHeader($collection->first());

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $num = 0;
        $collection->chunk(1000)->map(function ($chunk) use (&$num) {
            $chunk->map(function ($item, $row) use (&$num) {
                $row = $row + 1;

                if ($row == 1) {
                    return null;
                }
                // 常规内容校验
                list(
                    $mallId,
                    $mallName,
                    $branch,
                    $largeClassify,
                    $smallClassify,
                    $label,
                    $topList,
                    $price,
                    $rating,
                    $star,
                    $phone,
                    $commentNum,
                    $businessStatus,
                    $province,
                    $city,
                    $district,
                    $area,
                    $address,
                    $lng,
                    $lat,
                    $car,
                    $healthcare,
                    $food,
                    $study,
                    $scenicSpot,
                    $Shopping,
                    $marry,
                    $beauty,
                    $homeFurnishing,
                    $cinema,
                    $homestay,
                    $parentChild,
                    $recreation,
                    $hotel,
                    $KSong,
                    $pat,
                    $life,
                    $sport,
                    $traffic,
                    $foodRatio,
                    $shopTotalCount,
                    $grade
                    ) = $item;
                $facilitiesRating  = '';
                $environmentRating = '';
                $serviceRating     = '';

                //评分处理
                if (mb_strlen($rating) >= 20) {
                    $facilitiesRating  = substr(explode(' ', trim($rating))[0] ?? '', -3);
                    $environmentRating = substr(explode(' ', trim($rating))[1] ?? '', -3);
                    $serviceRating     = substr(explode(' ', trim($rating))[2] ?? '', -3);
                } else {
                    $this->ratingArr[] = [
                        'mallId' => $mallId,
                        'rating' => $rating,
                    ];
                }

                $tempLatLng = CoordinateService::gcj02ToWgs84($lng, $lat);

                //特别的处理
                switch ((int)$businessStatus) {
                    case 0 :
                    case 3 :
                        $mallStatus = SiteLocationMallModel::MALL_BUSINESS_STATUS_OK;
                        break;
                    case 1 :
                        $mallStatus = SiteLocationMallModel::MALL_BUSINESS_STATUS_CLOSE;
                        break;
                    default:
                        $mallStatus = SiteLocationMallModel::MALL_BUSINESS_STATUS_OK;
                }

                $siteLocationMall                    = SiteLocationMallModel::query()
                    ->updateOrCreate([
                        'mallId' => $mallId
                    ]);
                if (!$siteLocationMall->wgNumber) {
                    $siteLocationMall->wgNumber = 'SC11' . str_pad($siteLocationMall->id, 6, '0', STR_PAD_LEFT);
                }
                $siteLocationMall->mallName          = (string)$mallName;
                $siteLocationMall->branch            = (string)$branch;
                $siteLocationMall->largeClassify     = (string)$largeClassify;
                $siteLocationMall->smallClassify     = (string)$smallClassify;
                //$siteLocationMall->label             = (string)$label;
                $siteLocationMall->topList           = (string)$topList;
                $siteLocationMall->price             = (int)$price;
                $siteLocationMall->facilitiesRating  = (float)$facilitiesRating;
                $siteLocationMall->environmentRating = (float)$environmentRating;
                $siteLocationMall->serviceRating     = (float)$serviceRating;
                $siteLocationMall->star              = (float)$star;
                $siteLocationMall->phone             = (string)$phone;
                $siteLocationMall->commentNum        = (int)$commentNum;
                $siteLocationMall->mallStatus        = (int)$mallStatus;
                $siteLocationMall->province          = (string)$province;
                $siteLocationMall->city              = (string)$city;
                $siteLocationMall->district          = (string)$district;
                $siteLocationMall->area              = (string)$area;
                $siteLocationMall->address           = (string)$address;
                $siteLocationMall->lng               = $tempLatLng['lon'];
                $siteLocationMall->lat               = $tempLatLng['lat'];
                $siteLocationMall->car               = (int)$car;
                $siteLocationMall->healthcare        = (int)$healthcare;
                $siteLocationMall->food              = (int)$food;
                $siteLocationMall->study             = (int)$study;
                $siteLocationMall->scenicSpot        = (int)$scenicSpot;
                $siteLocationMall->Shopping          = (int)$Shopping;
                $siteLocationMall->marry             = (int)$marry;
                $siteLocationMall->beauty            = (int)$beauty;
                $siteLocationMall->homeFurnishing    = (int)$homeFurnishing;
                $siteLocationMall->cinema            = (int)$cinema;
                $siteLocationMall->homestay          = (int)$homestay;
                $siteLocationMall->parentChild       = (int)$parentChild;
                $siteLocationMall->recreation        = (int)$recreation;
                $siteLocationMall->hotel             = (int)$hotel;
                $siteLocationMall->KSong             = (int)$KSong;
                $siteLocationMall->pat               = (int)$pat;
                $siteLocationMall->life              = (int)$life;
                $siteLocationMall->sport             = (int)$sport;
                $siteLocationMall->traffic           = (int)$traffic;
                $siteLocationMall->foodRatio         = (float)$foodRatio;
                $siteLocationMall->shopTotalCount    = (int)$shopTotalCount;
                $siteLocationMall->grade             = ProgrammingEnum::GRADE_INVERSE_CODING_MAPPING[(string)$grade] ?? 2;
                $siteLocationMall->save();
                dump(++$num);

            })->filter();
        });
        dump($this->ratingArr);
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "商场ID",
            "商场名称",
            "分店",
            "大分类",
            "小分类",
            "标签",
            "榜单",
            "价格",
            "评分",
            "星级",
            "电话",
            "评论数",
            "营业状态",
            "省份",
            "城市",
            "区县",
            "区域",
            "地址",
            "商场经度",
            "商场纬度",
            "养车/用车",
            "医疗健康",
            "美食店铺数",
            "学习培训",
            "景点/周边游",
            "购物",
            "结婚",
            "丽人",
            "家居",
            "电影演出赛事",
            "榛果民宿",
            "亲子",
            "休闲娱乐",
            "酒店",
            "K歌",
            "宠物",
            "生活服务",
            "运动健身",
            "交通枢纽",
            "美食店铺占比",
            "店铺总数",
            "商场分级",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
